import {
  ProForm,
  ProTable,
} from '@ant-design/pro-components';
import { Form, message, Steps, Button, Table, Drawer, } from 'antd';
import { request } from '../../utils/request.ts';
import { useEffect, useState, useRef, } from 'react';
import RemoteSelect from '../../components/RemoteSelect/index.jsx';
import { getUserData } from '../../utils/const.ts';
import { getColumns } from './const.jsx';
import './index.css';

const Add = ({ open, setOpen, reload, record, }) => {
  const actionRef = useRef();
  const [form] = Form.useForm();
  const [current, setCurrent] = useState(0);
  const [tableData, setTableData] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedStudents, setSelectedStudents] = useState([]);
  const [classIdState, setClassIdState] = useState();

  // useEffect(() => {
  //   if (open) {
  //     const userStr = getUserData();
  //     const user = JSON.parse(userStr);
  //     setLevel(user.level);
  //     const initial = {
  //       ...record,
  //       userId: user.level === 2 ? user?.id : undefined,
  //     };
  //     form.setFieldsValue(initial);
  //   }
  // }, [open, record, form]);

  const handleSelectChange = (keys, rows) => {
    setSelectedRowKeys(keys);
    setSelectedStudents(rows);
    form.setFieldsValue({
      num: keys.length,
      totalPrice: form.getFieldValue('cardSinglePrice') * keys.length,
    });
  };

  const handleRemoveStudent = (id) => {
    const newKeys = selectedRowKeys.filter(key => key !== id);
    setSelectedRowKeys(newKeys);
    setSelectedStudents(selectedStudents.filter(s => s.id !== id));
    form.setFieldsValue({
      num: newKeys.length,
      totalPrice: form.getFieldValue('cardSinglePrice') * newKeys.length,
    });
  };

  const steps = [
    {
      title: '第一步',
      fields: ['cardId', 'classId'],
      content: <>
        <RemoteSelect
          name="cardId"
          label="证书"
          rules={[{ required: true, message: '请选择证书' }]}
          fetchUrl="/api/card/pageList"
          fetchMethod="POST"
          fetchParams={{ type: '2' }}
          mapOption={item => ({ label: item.name, value: item.id, price: item.price, })}
          onChange={(value, option) => {
            form.setFieldsValue({ cardName: option.label, cardPrice: option.price, cardSinglePrice: option.price });
          }}
        />
        <ProForm.Item name="cardName" noStyle>
          <input type="hidden" />
        </ProForm.Item>
        <ProForm.Item name="cardPrice" noStyle>
          <input type="hidden" />
        </ProForm.Item>
        <ProForm.Item name="cardSinglePrice" noStyle>
          <input type="hidden" />
        </ProForm.Item>
        <RemoteSelect
          name="classId"
          label="班级"
          rules={[{ required: true, message: '请选择班级' }]}
          fetchUrl="/api/class/pageList"
          fetchMethod="POST"
          mapOption={item => ({ label: item.name, value: item.id })}
        />
      </>,
    },
    {
      title: '第二步',
      fields: [],
      content: <>
        <h3 className='title'>已选学员</h3>
        <Table
          dataSource={selectedStudents}
          columns={[
            ...getColumns(),
            {
              title: '操作',
              render: (_, record) => (
                <a onClick={() => handleRemoveStudent(record.id)}>移除</a>
              ),
            },
          ]}
          rowKey="id"
          pagination={false}
          size="small"
        />
        <h3 className='title'>添加学员</h3>
        <ProTable
          actionRef={actionRef}
          rowKey="id"
          options={false}
          // search={false}
          request={async ({ current, status, ...other }) => {
            const data = {
              ...other,
              pageNum: current,
              status: status || -1,
              classId: classIdState || -1,
            }
            let res = await request('/api/user/student', {
              method: 'POST',
              data,
            });
            const { records, total } = res?.data || {};
            setTableData(records || []);
            return {
              data: records || [],
              total: total || 0,
            };
          }}
          columns={getColumns({ isNameSearch: true, isMobilephoneSearch: true,})}
          rowSelection={{
            selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
            selectedRowKeys,
            onChange: handleSelectChange,
            getCheckboxProps: (record) => ({
              disabled: false,
            }),
          }}
        />
        <ProForm.Item name="num" noStyle>
          <input type="hidden" />
        </ProForm.Item>
        <ProForm.Item name="totalPrice" noStyle>
          <input type="hidden" />
        </ProForm.Item>
      </>,
    },
    {
      title: '第三步',
      fields: [],
      content: <>
        <ProForm.Item name="cardName" label="证书名称">
          <input
            type="text"
            readOnly
            className="readonly-input"
            tabIndex={-1}
            aria-label="证书名称"
          />
        </ProForm.Item>
        <ProForm.Item name="num" label="申请人数">
          <input
            type="text"
            readOnly
            className="readonly-input"
            tabIndex={-1}
            aria-label="申请人数"
          />
        </ProForm.Item>
        <ProForm.Item name="cardPrice" label="证书价格">
          <input
            type="text"
            readOnly
            className="readonly-input"
            tabIndex={-1}
            aria-label="证书价格"
          />
        </ProForm.Item>
        <ProForm.Item name="cardSinglePrice" label="证书单价">
          <input
            type="text"
            readOnly
            className="readonly-input"
            tabIndex={-1}
            aria-label="证书单价"
          />
        </ProForm.Item>
        <ProForm.Item name="totalPrice" label="总价">
          <input
            type="text"
            readOnly
            className="readonly-input"
            tabIndex={-1}
            aria-label="总价"
          />
        </ProForm.Item>
      </>,
    },
  ];

  const items = steps.map((item) => ({
    key: item.title,
    title: item.title,
  }));

  const prev = () => {
    setCurrent(current - 1);
  };

  const next = async () => {
    const fields = steps[current].fields;
    try {
      if (fields && fields.length > 0) {
        await form.validateFields(fields);
      }
      setCurrent(current + 1);
      if (current === 0) {
        const data = {
          pageNum: 0,
          status: -1,
          classId: -1,
        }
        let res = await request('/api/user/student', {
          method: 'POST',
          data,
        });
        const record = res?.data || [];
        setSelectedStudents(record);
        setSelectedRowKeys(record?.map(item => item.id));
        form.setFieldsValue({
          num: record?.length,
          totalPrice: form.getFieldValue('cardSinglePrice') * record?.length,
        });
      }
    } catch (err) {
      // 校验失败，不做跳转
    }
  };

  const onFinish = async(values) => {
    let res = await request('/api/studentCard/save', {
      method: 'POST',
      data: {
        student: selectedStudents.map(item => item.id),
        cardId: values.cardId,
      },
    });
    if (res?.code === 200) {
      message.success('提交成功');
      setOpen(false);
      setCurrent(0);
      form.resetFields();
      reload();
    }
  }

  return (
    <Drawer
      title="新增证书"
      open={open}
      onClose={() => {
        setOpen(false);
        form.resetFields();
        setCurrent(0);
      }}
      width={'80%'}
      submitter={false}
      layout="horizontal"
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 12 }}
    >
      <Steps current={current} items={items} />
      <ProForm
        form={form}
        onFinish={onFinish}
        onValuesChange={(changed, all) => {
          if ('classId' in changed) {
            setClassIdState(changed.classId);
            if (current === 1 && actionRef?.current) {
              actionRef.current.reload();
            }
          }
        }}
        submitter={false}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 12 }}
      >
          <div className="steps-content">
            {steps.map((step, idx) => (
              <div key={step.title} style={{ display: idx === current ? 'block' : 'none' }}>
                {step.content}
              </div>
            ))}
          </div>
          <div className="steps-action">
            {current > 0 && (
              <Button
              onClick={() => prev()}
              >
                上一步
              </Button>
            )}
            {current < steps.length - 1 && (
              <Button type="primary" onClick={() => next()}>
                下一步
              </Button>
            )}
            {current === steps.length - 1 && (
              <Button type="primary" htmlType="submit">
                确认提交
              </Button>
            )}
          </div>
      </ProForm>
    </Drawer>
  );
};
export default Add;